/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.servlet.admin;

import controller.servlet.SignupServlet;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import util.FileUpload;
import model.dao.RoleDAO;
import model.dao.UserDAO;
import model.dao.service.RoleDAOService;
import model.dao.service.UserDAOService;
import model.entities.Role;
import model.entities.User;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import util.Constants;

/**
 *
 * @author Admin
 */
public class UserManagement extends HttpServlet {

    private final UserDAOService USER_SERVICE = UserDAO.getInstance();
    private final RoleDAOService ROLE_SERVICE = RoleDAO.getInstance();

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String action = request.getParameter("action");
        if (action != null) {
            switch (action) {
                case "requestViewAll":
                    loadUserList(request, response);
                    break;
                case "requestEdit":
                    requestEdit(request, response);
                    break;
                case "requestAddnew":
                    requestAddnew(request, response);
                    break;
                case "requestRestore":
                    requestRestore(request, response);
                    break;
                case "requestRemove":
                    requestRemove(request, response);
                    break;
                case "requestDelete":
                    requestDelete(request, response);
                    break;

            }
        } else {
            loadUserList(request, response);
        }

    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String action = request.getParameter("action");
        String page = request.getParameter("p");
        if (action != null) {
            switch (action) {
                case "update":
                    update(request, response);
                    break;
                case "addnew":
                    addNewUser(request, response);
                    break;
                case "search":
                    findUsers(request, response);
                    break;

            }
        }
        
                
    }

    private void loadUserList(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<User> usersList = USER_SERVICE.getAllUser();
        request.setAttribute(util.Constants.USER_LIST, usersList);
        request.setAttribute(util.Constants.PAGE, "userlist");
        request.getRequestDispatcher(util.Constants.URL_ADMIN).forward(request, response);
    }

    private void requestViewAll(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setAttribute(util.Constants.PAGE, "edit");
        request.getRequestDispatcher(util.Constants.URL_ADMIN).forward(request, response);
    }

    private void requestEdit(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int userID = Integer.parseInt(request.getParameter("id"));
        User user = USER_SERVICE.getUserByID(userID);
        if (user != null) {
            request.setAttribute(util.Constants.USER_EDIT, user);
        } else {
            request.setAttribute(util.Constants.MSG_RESULT, "Error while load info...");
        }
        request.setAttribute(util.Constants.PAGE, "edit");
        request.getRequestDispatcher(util.Constants.URL_ADMIN).forward(request, response);
    }

    private void requestAddnew(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setAttribute(util.Constants.PAGE, "addnew");
        request.getRequestDispatcher(util.Constants.URL_ADMIN).forward(request, response);
    }

    private void requestRestore(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int userID = Integer.parseInt(request.getParameter("id"));
        User user = USER_SERVICE.getUserByID(userID);
        if (USER_SERVICE.restoreUser(user)) {
            loadUserList(request, response);
        } else {
            request.setAttribute(util.Constants.MSG_RESULT, "Can't change status to active!!!");
        }
    }

    private void requestRemove(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int userID = Integer.parseInt(request.getParameter("id"));
        User user = USER_SERVICE.getUserByID(userID);
        if (!user.getRole().getRoleName().equals("Administrator")) {
            if (USER_SERVICE.removeUser(user)) {
                loadUserList(request, response);
            } else {
                request.setAttribute(util.Constants.MSG_RESULT, "Can't change status to disactive!!!");
            }
        } else {
            request.setAttribute(util.Constants.MSG_RESULT, "Can't remove user is a Administrator!!!");
            loadUserList(request, response);
        }
    }

    private void requestDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int userID = Integer.parseInt(request.getParameter("id"));
        User user = USER_SERVICE.getUserByID(userID);
        if (!user.getRole().getRoleName().equals("Administrator")) {
            if (USER_SERVICE.deleteUser(userID)) {
                loadUserList(request, response);
            } else {
                request.setAttribute(util.Constants.MSG_RESULT, "Can't delete user!!!");
            }
        } else {
            request.setAttribute(util.Constants.MSG_RESULT, "Can't delete user is a Administrator!!!");
            loadUserList(request, response);
        }
    }

    private void update(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        request.setCharacterEncoding("UTF-8");
        String userID = request.getParameter("userid");
        int id = Integer.valueOf(userID);
        String pwd = request.getParameter("password");
        String fullName = new String(request.getParameter("fullName").getBytes(
                "iso-8859-1"), "UTF-8");
        String day = request.getParameter("birthday");
        boolean gender = request.getParameter("gender").equals("male");
        String idCard = request.getParameter("IdCard");
        String address = new String(request.getParameter("address").getBytes(
                "iso-8859-1"), "UTF-8");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String password = util.MD5.encryptMD5(pwd);
        String ro = request.getParameter("role");
        int rs = Integer.parseInt(ro);
        Role role = ROLE_SERVICE.getRoleByID(rs);
        String userName = USER_SERVICE.getUserByID(id).getUserName();

        String imagePath = null;

        User user = new User(id, userName, password, fullName, java.sql.Date.valueOf(day), gender, idCard, address, email, phone, imagePath, role, idCard, gender);
        if (USER_SERVICE.updateUserByAdmin(user)) {
            response.sendRedirect("/JudiBlog" + Constants.URL_USERMANAGE);

        } else {
            request.setAttribute(Constants.MSG_RESULT, "Edit fail");
            request.setAttribute(Constants.PAGE, "edit");
            request.getRequestDispatcher(Constants.URL_ADMIN).forward(request, response);
        }

    }

    private void addNewUser(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, ServletException, IOException {
        try {
            response.setContentType("text/html;charset=UTF-8");
            if (request.getCharacterEncoding() == null) {
                request.setCharacterEncoding("UTF-8");
            }
            String userName = request.getParameter("userName");
            String pwd = request.getParameter("pwd");
            String fullName = new String(request.getParameter("fullName").getBytes(
                "iso-8859-1"), "UTF-8");
            
            String day = request.getParameter("birthday_day");
            String month = request.getParameter("birthday_month");
            String year = request.getParameter("birthday_year");
            String bd = year + "/" + month + "/" + day;
            SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
            Date utilBD = df.parse(bd);
            java.sql.Date birthday = new java.sql.Date(utilBD.getTime());
            boolean gender = request.getParameter("gender").equals("male");
            String idCard = request.getParameter("idCard");
            String address = new String(request.getParameter("address").getBytes(
                "iso-8859-1"), "UTF-8");
            String email = request.getParameter("email");
            String phone = request.getParameter("phone");
            String password = util.MD5.encryptMD5(pwd);
            String ro = request.getParameter("role");
            int rs = Integer.parseInt(ro);
            Role role = ROLE_SERVICE.getRoleByID(rs);
            String imagePath = null;
            if (!USER_SERVICE.checkUser(userName)) {
                User user = new User(1, userName, password, fullName, birthday, gender, idCard, address, email, phone, imagePath, role, null, true);
                if (USER_SERVICE.createUser(user)) {
                    response.sendRedirect("/JudiBlog" + Constants.URL_USERMANAGE);

                } else {
                    request.setAttribute(Constants.MSG_RESULT, "Insert fail");
                    request.setAttribute(Constants.PAGE, "addnew");
                    request.getRequestDispatcher(Constants.URL_ADMIN).forward(request, response);
                }
            } else {

                request.setAttribute(util.Constants.MSG_RESULT, "User name is existed !!!");
                request.setAttribute(Constants.PAGE, "addnew");
                request.getRequestDispatcher(util.Constants.URL_ADMIN).forward(request, response);
            }
        } catch (ParseException ex) {
            Logger.getLogger(UserManagement.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void findUsers(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String key = request.getParameter("key");
        String value = request.getParameter("value");
        List<User> userList = USER_SERVICE.findUsers(key, value);
        if (userList.isEmpty()) {
            request.setAttribute(util.Constants.MSG_RESULT, "No result for " + value);
        } else {
            request.setAttribute(util.Constants.USER_LIST, userList);
        }
        request.setAttribute(util.Constants.PAGE, "userlist");
        request.getRequestDispatcher(util.Constants.URL_ADMIN).forward(request, response);

    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
